<template>
  <el-row>
    <!-- 添加角色 -->
    <el-col style="margin-bottom: 10px">
      <el-button type="primary" @click="addDialogVisible = true">
        添加角色
      </el-button>
    </el-col>

    <!-- 角色列表 -->
    <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bd-bottom', index1 === 0 ? 'bd-top' : '', 'vcenter']"
            v-for="(item1, index1) in scope.row.children"
            :key="item1.id"
          >
            <!-- 一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="romoveRightById(scope.row, item1.id)">{{
                item1.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级三级权限 -->
            <el-col :span="19">
              <el-row
                :class="[index2 !== 0 ? 'bd-top' : '', 'vcenter']"
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
              >
                <!-- 二级权限 -->
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="romoveRightById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span="18">
                  <el-tag
                    v-for="(item3, index3) in item2.children"
                    :key="item3.id"
                    type="warning"
                    closable
                    @close="romoveRightById(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#" />
      <el-table-column label="角色名称" prop="roleName" />
      <el-table-column label="角色描述" prop="roleDesc" />
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="getRoleInfo(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeRoleById(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-setting"
            size="mini"
            @click="showSetRightDialog(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
    >
      <!-- 添加角色 -->
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        label-width="80px"
        ref="addRolesFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="allRightsTree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
import {
  getRolesList,
  addRoleInfo,
  getRoleInfoById,
  editRoleInfoById,
  removeRoleInfoById,
} from 'network/roles'
import { removeRightById, getRightsTree, allotRights } from 'network/rights'
export default {
  name: 'RolesListArea',
  data() {
    return {
      rolesList: [],
      addRolesForm: {
        roleName: '',
        roleDesc: '',
      },
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [],
      },
      addDialogVisible: false,
      editDialogVisible: false,
      editRoleForm: {},
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        roleDesc: [],
      },
      setRightDialogVisible: false,
      allRightsTree: [],
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      defKeys: [],
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const res = await getRolesList()
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败!')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    addRoleDialogClosed() {
      this.addDialogVisible = false
      this.$refs.addRolesFormRef.resetFields()
    },
    addRole() {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await addRoleInfo(this.addRolesForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
          return
        }
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    async getRoleInfo(id) {
      this.editDialogVisible = true
      const res = await getRoleInfoById(id)
      // console.log(res)
      if (res.meta.status !== 200)
        return this.$message.eror('获取角色信息失败!')
      this.editRoleForm = res.data
    },
    editDialogClosed() {
      this.editDialogVisible = false
      this.$refs.editRoleFormRef.resetFields()
    },
    async editRoleInfo() {
      const res = await editRoleInfoById(this.editRoleForm)
      if (res.meta.status !== 200) return this.$message.error('修改角色失败!')
      this.$message.success('修改角色成功')
      this.getRolesList()
      this.editDialogVisible = false
    },
    async removeRoleById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }
      const res = await removeRoleInfoById(id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败!')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    async romoveRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限,是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult === 'cancel') return this.$message.info('取消了删除')
      const res = await removeRightById(role.id, rightId)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      // this.getRolesList()页面会重新刷新
      role.children = res.data
    },
    async showSetRightDialog(role) {
      // 获取所有权限数据
      this.roleId = role.id
      const res = await getRightsTree()
      if (res.meta.status !== 200)
        return this.$message.error('获取权限数据失败!')
      this.allRightsTree = res.data
      // console.log(this.allRightsTree)
      this.defKeys.length = 0
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idStr = keys.join(',')
      const res = await allotRights(this.roleId, idStr)

      if (res.meta.status !== 200) return this.$message.error('分配权限失败!')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}
</style>